import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/foot.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/components/images/image_load_one.dart';
import 'package:wallpaper/components/input/normal_input.dart';

class FoodPage extends StatefulWidget {
  const FoodPage({super.key});

  @override
  State<FoodPage> createState() => _FoodPageState();
}

class _FoodPageState extends State<FoodPage>
    with AutomaticKeepAliveClientMixin {
  // 文本控制器
  TextEditingController textEditingController = TextEditingController();
  List foods = [];
  bool isLoading = false;

  void getData() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (textEditingController.text.isEmpty) {
      // return TDToast.showText('请输入食物名称', context: context);
    }
    setState(() {
      foods = [];
      isLoading = true;
    });
    try {
      Response res = await getFoods(keyword: textEditingController.text);
      if (res.data['code'] == 200) {
        setState(() {
          isLoading = false;
          foods = res.data['data'];
        });
      }
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      // ignore: use_build_context_synchronously
      // TDToast.showText('暂未找到相关食物', context: context);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '美食',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        toolbarHeight: 0,
        elevation: 0,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          Image.asset('lib/assets/icon/8.png', width: 30, height: 30),
          const SizedBox(width: 10),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          children: [
            _buildSearch(),
            if (foods.isEmpty && !isLoading) Empty(),
            if (isLoading && foods.isEmpty) _buildLoading(),
            _buildFoodList(),
            SizedBox(height: 10)
          ],
        ),
      ),
    );
  }

  Widget _buildSearch() {
    return Container(
        padding: EdgeInsets.only(left: 10, right: 10, bottom: 5, top: 10),
        color: Theme.of(context).colorScheme.primaryContainer,
        child: Row(
          children: [
            Expanded(
              child: NormalInput(
                height: 35,
                icon: Icon(Icons.food_bank_sharp),
                controller: textEditingController,
                title: '食物名称',
                onSubmitted: (v) {
                  getData();
                },
              ),
            ),
            IconButton(
                onPressed: () {
                  getData();
                },
                icon: Icon(Icons.search))
          ],
        ));
  }

  Widget _buildFoodList() {
    return Expanded(
      child: ListView.builder(
        itemCount: foods.length,
        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Theme.of(context).colorScheme.shadow,
                    spreadRadius: 1,
                    blurRadius: 2,
                    offset: Offset(0, 2), // changes position of shadow
                  ),
                ]),
            margin: EdgeInsets.only(top: 20, left: 10, right: 10),
            padding: EdgeInsets.all(15),
            child: Column(
              children: [
                Text(
                  foods[index]['name'],
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  foods[index]['description'],
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.onSurface,
                  ),
                ),
                ImageLoadOne(imageUrl: foods[index]['image']),
                SizedBox(height: 10),
                Container(
                  padding: EdgeInsets.all(5),
                  width: double.infinity,
                  child: Text(
                    '配料：',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                for (int i = 0; i < foods[index]['materials'].length; i++)
                  Container(
                    padding: EdgeInsets.only(top: 5, left: 5, right: 5),
                    width: double.infinity,
                    child: Text(
                      foods[index]['materials'][i],
                      style: TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                SizedBox(height: 10),
                Container(
                  padding: EdgeInsets.all(5),
                  width: double.infinity,
                  child: Text(
                    '做法：',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                for (int i = 0; i < foods[index]['practice'].length; i++)
                  Container(
                    padding: EdgeInsets.only(top: 5, left: 5, right: 5),
                    width: double.infinity,
                    child: Text(
                      '${i + 1}、${foods[index]['practice'][i]}',
                      style: TextStyle(fontWeight: FontWeight.w500),
                    ),
                  ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      onPressed: () {},
                      icon: Icon(Icons.star_outline),
                    ),
                    IconButton(
                      onPressed: () {},
                      // 点赞
                      icon: Icon(Icons.thumb_up_outlined),
                    ),
                    IconButton(
                      onPressed: () {},
                      // 收藏
                      icon: Icon(Icons.favorite_border),
                    )
                  ],
                )
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildLoading() {
    return SizedBox(
      height: MediaQuery.of(context).size.height - 100,
      child: Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
